<template>
  <div class="container">
    <headMenu />
    <a-card class="general-card" :title="'查询' + $t(menusName)">
      <!--  查询   -->
      <a-row>
        <a-col :flex="1">
          <a-form  :model="pageData" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }" label-align="left">
            <a-row :gutter="18">
              <a-col :span="9">
                <a-form-item field="number" label="编号">
                  <a-input placeholder="编号" v-model="pageData.id" />
                </a-form-item>
              </a-col>
              <a-col :span="9">
                <a-form-item field="name" label="用户名称">
                  <a-input v-model="pageData.name" placeholder="用户名称" />
                </a-form-item>
              </a-col>

              <a-col :span="9">
                <a-form-item field="createdTime" :label="$t('searchTable.form.createdTime')">
                  <a-range-picker @clear="clearTime" style="width: 100%" v-model="pageData.createdTime" />
                </a-form-item>
              </a-col>
              <a-col :span="9">
                <a-form-item field="status" :label="$t('searchTable.form.status')">
                  <!--      <a-select
                    :options="statusOptions"
                    v-model="pageData.status"
                    :placeholder="$t('searchTable.form.selectDefault')"
                  /> -->

                  <a-select v-model="pageData.status" :style="{ width: '320px' }"
                    :placeholder="$t('searchTable.form.selectDefault')">
                    <a-option :value="1">启用</a-option>
                    <a-option :value="0">冻结</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>

        <a-col :flex="'86px'" style="text-align: right; position: relative; right: 200px">
          <a-space direction="vertical" :size="18">
            <a-button type="primary" @click="search">
              <template #icon>
                <icon-search />
              </template>
              {{ $t('searchTable.form.search') }}
            </a-button>
            <a-button @click="reset">
              <template #icon>
                <icon-refresh />
              </template>
              {{ $t('searchTable.form.reset') }}
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-row style="margin-bottom: 16px">
        <a-col :span="16">
          <a-space>
            <a-button type="primary" @click="updateAndAdd(undefined)">
              <template #icon>
                <icon-plus />
              </template>
              {{ $t('searchTable.operation.create') }}
            </a-button>
          </a-space>
          <a-space style="margin-left: 20px;">
            <a-upload :show-file-list="false" name="file" action="/api/user/import" :headers="{ satoken: satoken }"
              @success="successRes">
              <template #upload-button>
                <a-button>
                  {{ $t('searchTable.operation.import') }}
                </a-button>
              </template>
            </a-upload>
          </a-space>
        </a-col>
        <a-col :span="8" style="text-align: right">
          <a-button @click="subitmDeleteIds">
            <template #icon>
              <icon-delete />
            </template>
            批量删除
          </a-button>
        </a-col>
      </a-row>
      <!--  渲染数据  -->
      <a-spin :loading="loading" tip="This may take a while..." style="width: 100%">
        <a-table row-key="urId" :bordered="false" :data="data" @selection-change="selectionChange" :row-selection="{
            type: 'checkbox',
            showCheckedAll: true,
            checkStrictly: true,
          }" style="margin-top: 30px" :pagination="false" :hoverable="true">
          <template #columns>
            <a-table-column title="编号" data-index="urId"></a-table-column>
            <a-table-column title="用户" data-index="urName"></a-table-column>
            <a-table-column title="性别">
              <template #cell="{ record }">
                {{ record.urSex == 1 ? '男' : '女' }}
              </template>
            </a-table-column>
            <a-table-column title="用户名称" data-index="urUsername"></a-table-column>
            <a-table-column title="创建时间" data-index="createTime"></a-table-column>
            <a-table-column title="邮箱" data-index="urEmail"></a-table-column>
            <a-table-column title="头像">
              <template #cell="{ record }">
                <a-avatar>
                  <img alt="avatar" :src="record.urAvatar" />
                </a-avatar>
              </template>
            </a-table-column>

            <a-table-column title="状态">
              <template #cell="{ record }">
                <a-badge :status="record.urStuats == 1 ? 'success' : 'processing'"
                  :text="record.urStuats == 1 ? '启用' : '冻结'" />
              </template>
            </a-table-column>

            <a-table-column title="修改">
              <template #cell="{ record }">
                <a-button @click="updateAndAdd(record.urId)" type="outline">编辑</a-button>
              </template>
            </a-table-column>

            <a-table-column title="重置密码">
              <template #cell="{ record }">
                <a-button @click="updatePassword(record.urId)" type="outline">
                  <icon-loop />
                </a-button>
              </template>
            </a-table-column>

            <a-table-column title="删除">
              <template #cell="{ record }">
                <a-popconfirm @ok="submitDelete(record.urId)" content="Are you sure you want to delete?">
                  <a-button>
                    <template #icon>
                      <icon-delete />
                    </template>
                  </a-button>
                </a-popconfirm>
              </template>
            </a-table-column>
          </template>
        </a-table>

        <!--  分页  -->
        <a-pagination :total="pageData.totalCount" show-jumper show-page-size show-total show-current
          :current="pageData.page" :page-size="pageData.limit" :page-size-options="[10, 20, 50, 100]" @change="changePage"
          @page-size-change="limitChange" />
      </a-spin>
      <!--  编辑和添加的对话框
       -->
      <a-modal :visible="ediVisible" @ok="handleSubmit" @cancel="handleCancel" width="500">
        <template #title>{{ form.urId ? '编辑' : '添加' }}</template>
        <div>
          <a-form :model="form" :style="{ width: '100%' }">
            <a-form-item field="urName" label="用户名">
              <a-input :disabled="form.urId" v-model="form.urName" placeholder=" 用户名..." />
            </a-form-item>

            <a-form-item field="urUsername" label="用户名称">
              <a-input v-model="form.urUsername" placeholder=" 用户名称..." />
            </a-form-item>
            <a-form-item v-if="!form.urId" field="urPassword" label="用户密码">
              <a-input v-model="form.urPassword" placeholder=" 用户密码..." />
            </a-form-item>

            <a-form-item field="urEmail" label="邮箱">
              <a-input v-model="form.urEmail" placeholder=" 邮箱..." />
            </a-form-item>


            <a-form-item v-if="form.createTime" field="createTime" label="创建时间">
              <a-input disabled v-model="form.createTime" placeholder=" post..." />
            </a-form-item>

            <a-form-item field="urAvatar" label="头像">
              <uploadImg v-model="form.urAvatar" />
            </a-form-item>
            <a-form-item field="urStuats" label="状态">
              <a-select v-model="form.urStuats" :style="{ width: '320px' }" placeholder="选择状态">
                <a-option :value="1">启用</a-option>
                <a-option :value="0">冻结</a-option>
              </a-select>
            </a-form-item>

            <a-form-item field="urSex" label="性别">
              <a-select v-model="form.urSex" :style="{ width: '320px' }" placeholder="选择性别">
                <a-option :value="1">男</a-option>
                <a-option :value="0">女</a-option>
              </a-select>
            </a-form-item>

            <a-form-item field="urReId" label="角色">
              <a-select v-model="form.urReId" :style="{ width: '320px' }" placeholder="选择角色">
                <a-option v-for="role in roles" :key="role" :value="role.reId">{{ role.reName }}</a-option>
              </a-select>
            </a-form-item>
          </a-form>
        </div>
      </a-modal>
    </a-card>
  </div>
</template>

<script>
import admin from '@/api/sys/admin';
import headMenu from '@/components/headMenu/headMenu.vue';
import uploadImg from '@/components/uplod/uplodImg.vue';
import role from '@/api/sys/role';
export default {
  components: { headMenu, uploadImg },
  data() {
    return {
      satoken: localStorage.getItem('token'),
      roles: [],
      form: { urAvatar: '' },
      loading: true,
      deleteIds: [],
      ediVisible: false,
      menusName: this.$router.currentRoute.value.meta.locale,
      pageData: {
        id: '',
        name: '',
        createTime: '',
        endTiem: '',
        status: '',
        page: 1,
        limit: 10,
        totalCount: 0,
        totalPage: 0,
      },

      data: [],
    };
  },

  methods: {
    clearTime(){
      this.pageData.createTime = ""
        this.pageData.endTiem = ""
    },
    updatePassword(id) {
      admin.resetYourPassword(id).then(res => {
        if (res.data.success) {
          this.$notification.success("密码重置成功！默认密码：123");
        } else {
          this.$notification.error(res.data.message);
        }
      })
    },

    /**
     * 导入数据成功过后的回调函数
     */
    successRes(res) {
      if (res.response.code == 200) {
        this.$notification.success(res.response.data.data);
        res = null;
        this.getList()
      } else {
        this.$notification.success("批量导入数据失败！");
      }
    },
    /**
     * 获取图片地址
     */
    getImg(url) {
      // console.log(url);
      this.form.urAvatar = url;
    },
    /**
     * 取消弹窗
     */
    handleCancel() {
      this.ediVisible = false;
      this.form = { urAvatar: '' }
    },

    /**
     * 提交判断是添加还是删除
     */
    handleSubmit() {
      if (this.form.urId !== undefined) {
        this.updateSubmit();
      } else {
        this.addSumeit();
      }
    },

    /**
     * 提交修改
     */
    updateSubmit() {
      admin.updateAdd(this.form).then((res) => {
        if (res.data.code === 200) {
          //删除成功
          this.$notification.success('修改成功!');
          this.reset();
          this.form = { urAvatar: '' }
        } else {
          this.$notification.error('修改失败!');
        }
      });
    },

    /**
     *  添加提交
     */
    addSumeit() {
      admin.updateAdd(this.form).then((res) => {
        if (res.data.code === 200) {
          //添加成功
          this.$notification.success('添加成功!');
          this.reset();
          this.ediVisible = false;
          this.form = { urAvatar: '' }
        } else {
          this.$notification.error('添加失败!');
        }
      });
    },
    /**
     * 新添加的方法
     */
    addInfo() {
      this.ediVisible = true;
    },

    /**
     * 判断当前的修改还是添加
     */
    updateAndAdd(id) {
      this.getRoles();
      // console.log(id !== undefined);
      if (id !== undefined) {
        this.updateInfo(id);
      } else {
        this.addInfo();
      }
    },

    /**
     *  查询角色
     */
    getRoles() {
      role.findAll().then((res) => {
        this.roles = res.data.data.data;
      });
    },

    /**
     * 修改前先查询id
     */
    updateInfo(Id) {
      this.loading = true;
      admin.info(Id).then((res) => {
        this.form = res.data.data.user;
        //  console.log(this.form);
        this.ediVisible = true;
        this.loading = false;
      });
    },

    /**
     * 删除选中的方法
     */
    subitmDeleteIds() {
      admin.delete(this.deleteIds).then((res) => {
        if (res.data.code === 200) {
          //删除成功
          this.$notification.success('删除成功!');
          this.reset();
        } else {
          this.$notification.error('删除失败!');
        }
      });
    },
    /**
     * 查询数据
     */
    search() {
      //发送请求
      this.getList();
    },
    /**
     *  刷新查询的数据
     */
    reset() {
      this.ediVisible = false
      this.pageData = {
        id: '',
        name: '',
        createTime: '',
        endTime: '',
        status: '',
        page: '1',
        limit: 10,
        totalCount: 0,
        totalPage: 0,
      };
      this.getList();
    },

    /**
     *  选中
     */
    selectionChange(data) {
      this.deleteIds = data;
    },
    /**
     *  选择页码
     */
    changePage(currPage) {
      this.pageData.page = currPage;
      this.getList();
    },
    //选择分页大小
    limitChange(limit) {
      this.pageData.limit = limit;
      this.getList();
    },

    /**
     *  获取当前数据
     */
    getList() {
      var pageData = this.pageData
      var createdTime = ""
      //获取当前的开始时间和结束时间
      if (this.pageData.createdTime) {
        createdTime = this.pageData.createdTime
        this.pageData.createTime = this.pageData.createdTime[0];
        this.pageData.endTiem = this.pageData.createdTime[1];
        pageData.createdTime = ""
      }
      this.loading = true;
      admin.list(pageData).then((res) => {
        const page = res.data.data.page;
        this.data = page.list;
        this.pageData.page =
          page.currPage >= page.totalPage ? page.totalPage : page.currPage;
        this.pageData.limit = page.limit;
        this.pageData.totalCount = page.totalCount;
        this.pageData.totalPage = page.totalPage;
        this.pageData.createdTime = createdTime
        //console.log(createdTime);
        this.loading = false;
        // console.log(this.pageData);
      });
    },
    /**
     *  删除账号
     */
    submitDelete(id) {
      let data = [];
      data.push(id);
      admin.delete(data).then((res) => {
        if (res.data.code === 200) {
          //删除成功
          this.$notification.success('删除成功!');
          this.reset();
        } else {
          this.$notification.error('删除失败!');
        }
      });
    },
  },
  created() {
    this.getList();
  },
};
</script>

<style scoped lang="less">
.container {
  padding: 0 20px 20px 20px;
}

:deep(.arco-table-th) {
  &:last-child {
    .arco-table-th-item-title {
      margin-left: 16px;
    }
  }
}
</style>